// cloudfunctions/processWithdraw/index.js
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { recordId, status } = event
    
    // 检查参数
    if (!recordId || !['2', '3'].includes(status)) {
      return { success: false, message: '参数错误' }
    }
    
    // 开启事务
    const transaction = await db.startTransaction()
    
    try {
      // 1. 获取提现记录
      const recordRes = await transaction.collection('user_points')
        .where({
          'records.recordId': recordId
        })
        .get()
      
      if (!recordRes.data || recordRes.data.length === 0) {
        await transaction.rollback()
        return { success: false, message: '提现记录不存在' }
      }
      
      const pointsData = recordRes.data[0]
      const pointsDocId = pointsData._id
      
      // 2. 查找具体的提现记录
      const recordIndex = pointsData.records.findIndex(
        r => r.recordId === recordId && r.type === 2
      )
      
      if (recordIndex === -1) {
        await transaction.rollback()
        return { success: false, message: '提现记录不存在' }
      }
      console.log('1231',recordIndex);
      const withdrawRecord = pointsData.records[recordIndex]
      
     console.log('qweqw',withdrawRecord);
      // 4. 更新提现记录状态
      const updateData = { }
      
      
      // 5. 根据处理结果更新用户积分
      if (status == 2) { // 2=已结算（成功）
        updateData.points = _.inc(-withdrawRecord.amount)
        updateData.frozenPoints = _.inc(-withdrawRecord.amount)
      } else if (status == 3) { // 3=已拒绝
        updateData.frozenPoints = _.inc(-withdrawRecord.amount)
        // 添加积分返还记录
        updateData.records = _.unshift({
          recordId: `RET_${Date.now()}`,
          type: 3,              // 3=积分返还
          amount: withdrawRecord.amount,
          relatedRecordId: recordId,
          createTime: db.serverDate(),
          remark: `提现申请被拒绝，积分已返还`
        })
      }
      
      // 6. 执行更新
      await transaction.collection('user_points').doc(pointsDocId).update({
        data: updateData
      })
      
      // 7. 提交事务
      await transaction.commit()
      
      return { success: true, message: '提现处理成功' }
      
    } catch (error) {
      await transaction.rollback()
      throw error
    }
    
  } catch (error) {
    console.error('处理提现失败:', error)
    return { success: false, message: '处理提现失败' }
  }
}